﻿using System.Windows;
using System.Windows.Controls;

namespace AyurvedaUI
{
    /// <summary>
    /// Interaction logic for AyurvedaWindow.xaml
    /// </summary>
    public partial class AyurvedaWindow : Window
    {
        public AyurvedaWindow()
        {
            InitializeComponent();
        }

        private void SearchPlantBt_Click(object sender, RoutedEventArgs e)
        {
            foreach (TabItem tabItem in tabControlWorkSpace.Items)
            {
                if (tabItem.Header.Equals("Plant Search"))
                {
                    return;
                }
            }

            var tabItemSearchPlant = new TabItem();
            tabItemSearchPlant.Header = "Plant Search";
            tabItemSearchPlant.Content = new PlantSearch();
            InitialiseTabItem(tabItemSearchPlant);
        }

        private void PlantsAddNewBt_Click(object sender, RoutedEventArgs e)
        {
            foreach (TabItem tabItem in tabControlWorkSpace.Items)
            {
                if (tabItem.Header.Equals("Add Plant"))
                {
                    return;
                }
            }

            var tabItemAddPlant = new TabItem();
            tabItemAddPlant.Header = "Add Plant";
            tabItemAddPlant.Content = new PlantAdd();
            InitialiseTabItem(tabItemAddPlant);
        }

        private void InitialiseTabItem(TabItem tabItem)
        {
            tabItem.HorizontalContentAlignment = HorizontalAlignment.Left;
            tabItem.VerticalContentAlignment = VerticalAlignment.Top;
            tabControlWorkSpace.Items.Add(tabItem);
            tabControlWorkSpace.SelectedItem = tabItem;
            var contextMenuForTabItem = new ContextMenu();
            var itemClose = new MenuItem();
            contextMenuForTabItem.Items.Add(itemClose);
            itemClose.Header = "Close";
            tabItem.ContextMenu = contextMenuForTabItem;
            itemClose.Click += delegate { CloseTabItem_Click(tabItem); };
        }

        private static void CloseTabItem_Click(TabItem tabItem)
        {
            if (tabItem != null)
            {
                // find the parent tab control
                var tabControl = tabItem.Parent as TabControl;

                if (tabControl != null)
                {
                    tabControl.Items.Remove(tabItem); // remove tabItem
                }
            }
        }
    }
}
